<?php

namespace Wulian\Controller;

use Common\Controller\HomebaseController;

class CronController extends HomebaseController {

    public $m_download,$m_card,$m_user,$m_card_activate,$m_card_import,$m_package,$m_card_status,$m_cron,$m_flow_record,$m_order,$m_config;

    public $sleep_time = 50;    //毫秒
    function _initialize() {
        parent::_initialize();
        $this->m_download = M("WlDownload");
        $this->m_card= D("Wulian/WlCard");
        $this->m_user = M("Users");
        $this->m_card_activate = M("WlCardActivate");
        $this->m_card_import = M("WlCardImport");
        $this->m_package = M("WlPackage");
        $this->m_card_status = M("WlCardStatus");
        $this->m_cron = M("WlCron");
        $this->m_flow_record = D('WlFlowRecord');
        $this->m_order = M("WlOrder");
        $this->m_config = M("WlConfig");
    }

    /**
     * 增量包到期
     * 每天早上0点执行
     */
    function monthExpire(){
        $start_time = time();
        $log = "";
        $corn_list = $this->m_cron->where("cron_status=0 AND cron_endtime<'".time()."' AND cron_type=1")->select();
        foreach($corn_list AS $citem) {
            $log .= "cron_id:".$citem["cron_id"]."|卡号：".$citem["card_number"]."|";
            $card = $this->m_card->where(array("card_number" => $citem["card_number"]))->find();
            $mul_data = max($card["package_data_add"] - $citem["package_data"],0);
            $new_flow = $card["package_data_month"] + $mul_data;
            $telecom = new \Wulian\Lib\telecom();
            $telecom->poolNbr = $this->wl_config['flow_pool_id'];
            $package_data = round($new_flow / $this->wl_config["proportion"], 0);
            $log .= "流量值:".$package_data."|";
            $result = $telecom->modifyPoolMember($citem["card_number"], (int)$package_data);
            if ($result["Response"]["RspCode"] == '0000') {
                $log .= "成功";
                $res1 = $this->m_card->where(array("card_number" => $citem["card_number"]))->save(array("package_data_add" => $mul_data));
                if($res1)$this->m_cron->where(array("cron_id" => $citem["cron_id"]))->save(array("cron_status" => 1));
            }else{
                $cron_insert = array(
                    "cron_type"=>4,
                    "package_data"=>$citem["package_data"],
                    "order_id"=>0,
                    "cron_plus"=>2,
                    "cron_endtime"=>time(),
                    "cron_status"=>0,
                    'transaction_id'=>'',
                    'card_number'=>$citem["card_number"],
                );
                $this->m_cron->add($cron_insert);
                $log .= "失败|";
            }
        }
        $cost_time = time() - $start_time;
        addCronLog(1,$log,$cost_time);
    }

    /**
     * 订单失败处理
     * 每分钟处理
     */
    function orderFailRetry(){
        $start_time = time();
        $log = "";

        $user_card_recharge_error_num = 0;  //当前已经错误的次数
        $user_card_recharge_error_remind = 0;   //连续错误累计至这个时 提醒

        $cron_flow_error = $this->m_config->field("config_parame,config_value")->where(array("config_parame"=>array("IN","user_card_recharge_error_num,user_card_recharge_error_remind")))->find();
        foreach($cron_flow_error AS $citem){
            if($citem["config_parame"] == "user_card_recharge_error_num"){
                $user_card_recharge_error_num = $citem["config_value"];
            }else{
                $user_card_recharge_error_remind =  $citem["config_value"];
            }
        }

        $corn_list = $this->m_cron->where("cron_status=0 AND cron_endtime<'".time()."' AND cron_type=2")->select();
        foreach($corn_list AS $citem){
                $log .= "订单号：".$citem["order_id"]."|";
                //这里的含义其实是  失败的充值操作 月套餐 增量包 年续费
                $order = $this->m_order->where(array("order_id" => $citem["order_id"], 'order_status' => 0))->find();
                $card = $this->m_card->where(array("card_number" => $citem["card_number"]))->find();
                if ($order) {
                    $telecom = new \Wulian\Lib\telecom();
                    $telecom->poolNbr = $this->wl_config['flow_pool_id'];

                    if($order["package_type"] == 1 || $order["package_type"] == 3){ //月套餐 或者 年续费
                        $new_packe_data = $card["package_data_add"]+$order["package_data"];
                    }else{  //增量包
                        $new_packe_data = $card["package_data_month"]+$card["package_data_add"]+$order["package_data"];
                    }
                    $log .= "流量值:".$new_packe_data."|";

                    $package_data = round($new_packe_data / $this->wl_config["proportion"], 0);
                    $result = $telecom->modifyPoolMember($order["card_number"], (int)$package_data);
                    if ($result["Response"]["RspCode"] == '0000') {
                        successOrder($order["order_number"], $citem["transaction_id"]);
                        $this->m_cron->where(array("cron_id" => $citem["cron_id"]))->save(array("cron_status" => 1));
                        $log .= "成功|";
                        //充值成功  错误清0
                        if($user_card_recharge_error_num>0){
                            $this->m_config->where(array("config_parame"=>"user_card_recharge_error_num"))->save(array("config_value"=>0));
                        }
                    }else{
                        $log .= "失败|";
                        //超过错误次数 发邮件通知
                        if($user_card_recharge_error_num+1>=$user_card_recharge_error_remind){
                            errorEmailAction("定时任务-卡充值","充值接口请求失败");
                            $this->m_config->where(array("config_parame"=>"user_card_recharge_error_num"))->save(array("config_value"=>0));
                        }else{  //累加错误次数
                            $this->m_config->where(array("config_parame"=>"user_card_recharge_error_num"))->save(array("config_value"=>$user_card_recharge_error_num+1));
                        }

                    }
                }
        }
        $cost_time = time() - $start_time;
        addCronLog(2,$log,$cost_time);
    }

    /**
     * 月套餐流量到期 ，更新流量池限额为0
     */
    function packageExpire(){
        //这一步在每个月1号0点05分执行
        //执行截止日期 流量更新为0
        $start_time = time();
        $log = "";
        $card_list = $this->m_card->where("package_endtime<'".time()."' AND (package_data_month!=0 OR package_data_add!=0 )")->select();
        foreach($card_list AS $citem){
            $log .="卡号：".$citem["card_number"]."|";
            $telecom = new \Wulian\Lib\telecom();
            $telecom->poolNbr = $this->wl_config['flow_pool_id'];
            $package_data = 0;
            $result = $telecom->modifyPoolMember($citem["card_number"],(int)$package_data);
            if($result["Response"]["RspCode"] == '0000'){
                $log .="成功|";
                $this->m_card->where("card_id=".$citem["card_id"])->save(array("package_data_month"=>0,"package_data_add"=>0));
            }else{
                $cron_insert = array(
                    "cron_type"=>3,
                    "package_data"=>$citem["package_data_month"],
                    "order_id"=>0,
                    "cron_plus"=>2,
                    "cron_endtime"=>time(),
                    "cron_status"=>0,
                    'transaction_id'=>'',
                    'card_number'=>$citem["card_number"],
                );
                $this->m_cron->add($cron_insert);
                $log .="失败|";
            }
        }
        $cost_time = time() - $start_time;
        addCronLog(3,$log,$cost_time);
    }

    /**
     * 添加流量记录
     */
    function addCardMonth(){
        //每月1号0点01执行，先初始化一下
        //每月1号04点01执行，防止之前流量到期修改没有结束
        //每月1号09点01执行，防止之前流量到期修改没有结束
        //插入每张卡的月流量套餐信息
        $card_list = $this->m_card->select();
        foreach($card_list AS $citem){
            $this->m_flow_record->addFlowRecord($citem["card_number"],$citem);
        }
    }


    /**
     * 检测流量值是否低于1G 低于1G  充值
     * 每小时05分时执行
     */
    function authFlowRecharge(){
        $start_time = time();
        $log = "";
        $cron_flow_recharge_error_num = 0;  //当前已经错误的次数
        $cron_flow_recharge_error_remind = 0;   //连续错误累计至这个时 提醒

        $cron_flow_error = $this->m_config->field("config_parame,config_value")->where(array("config_parame"=>array("IN","cron_flow_recharge_error_num,cron_flow_recharge_error_remind")))->find();
        foreach($cron_flow_error AS $citem){
            if($citem["config_parame"] == "cron_flow_recharge_error_num"){
                $cron_flow_recharge_error_num = $citem["config_value"];
            }else{
                $cron_flow_recharge_error_remind =  $citem["config_value"];
            }
        }

        $telecom = new \Wulian\Lib\telecom();
        $telecom->poolNbr = $this->wl_config['flow_pool_id'];
        $pool = $telecom->getPoolQry();
        $pool_left = $pool["pool_left"];
        $flow_recharge_num = (date('j')<=20) ? 5:1;   //每个月20号之前如果流量不足那么一次冲入5G流量，20号之后不足一次冲1G流量
        $one_g = 1024*1024;
        if($pool && isset($pool["pool_left"])){
            if($pool_left<$one_g){
                $result = $telecom->flowPool($flow_recharge_num);
                if($result["IRESULT"] == '0'){
                    //充值成功  错误清0
                    if($cron_flow_recharge_error_num>0){
                        $this->m_config->where(array("config_parame"=>"cron_flow_recharge_error_num"))->save(array("config_value"=>0));
                    }
                    $log = "流量值充值,当前剩余流量:".$pool_left."KB,当月可用总流量:".$pool["pool_total"]."KB,当月已用流量:".$pool["pool_already"]."KB,充值流量:".$flow_recharge_num."G";
                    $data = array(
                        "cron"=>1,
                        "flow_pool_id"=> $this->wl_config['flow_pool_id'],
                        "flow_recharge_plus"=>$pool_left,
                        "flow_recharge_total"=>$pool["pool_total"],
                        "flow_recharge_already"=>$pool["pool_already"],
                        "flow_recharge_num"=>$flow_recharge_num,
                    );
                    addFlowRechargeLog($data);

                    $sms = new \Wulian\Lib\sms();
                    $sms->sendFlowRecharge(array("name"=>"定时服务","datetime"=>date("Y-m-d H:i:s"),"num"=>$flow_recharge_num."G"));
                }else{
                    //超过错误次数 发邮件通知
                    if($cron_flow_recharge_error_num+1>=$cron_flow_recharge_error_remind){
                        errorEmailAction("定时任务-流量池充值失败","充值接口请求失败");
                        $this->m_config->where(array("config_parame"=>"cron_flow_recharge_error_num"))->save(array("config_value"=>0));
                    }else{  //累加错误次数
                        $this->m_config->where(array("config_parame"=>"cron_flow_recharge_error_num"))->save(array("config_value"=>$cron_flow_recharge_error_num+1));
                    }
                }
            }
        }else{
            //超过错误次数 发邮件通知
            if($cron_flow_recharge_error_num+1>=$cron_flow_recharge_error_remind){
                errorEmailAction("定时任务-流量池充值失败","查看剩余流量接口访问失败");
                $this->m_config->where(array("config_parame"=>"cron_flow_recharge_error_num"))->save(array("config_value"=>0));
            }else{//累加错误次数
                $this->m_config->where(array("config_parame"=>"cron_flow_recharge_error_num"))->save(array("config_value"=>$cron_flow_recharge_error_num+1));
            }
            $log = "流量查询接口返回错误信息，请求失败";
        }
        $cost_time = time() - $start_time;
        addCronLog(5,$log,$cost_time);
    }


    /**
     * 月套餐到期处理失败的重新处理
     * 每5分钟处理一次
     */
    function packageExpireFailRetry(){
        $start_time = time();
        $log = "";
        $corn_list = $this->m_cron->where("cron_status=0 AND cron_type=3")->select();
        foreach($corn_list AS $citem){
            $card = $this->m_card->where(array("card_number"=>$citem['card_number']))->find();
            $log .="卡号：".$card["card_number"]."|";
            $telecom = new \Wulian\Lib\telecom();
            $telecom->poolNbr = $this->wl_config['flow_pool_id'];
            $package_data = 0;
            $result = $telecom->modifyPoolMember($card["card_number"],(int)$package_data);
            if($result["Response"]["RspCode"] == '0000'){
                $log .="成功|";
                $res1 = $this->m_card->where("card_id=".$card["card_id"])->save(array("package_data_month"=>0,"package_data_add"=>0));
                if($res1)$this->m_cron->where(array("cron_id" => $citem["cron_id"]))->save(array("cron_status" => 1));
            }else{
                $log .="失败|";
            }
        }
        $cost_time = time() - $start_time;
        addCronLog(6,$log,$cost_time);
    }

    /**
     * 增量包到期处理失败的重新处理
     * 每5分钟处理一次
     */
    function monthExpireFailRetry(){
        $start_time = time();
        $log = "";
        $corn_list = $this->m_cron->where("cron_status=0 AND cron_type=4")->select();
        foreach($corn_list AS $citem){
            $log .= "cron_id:".$citem["cron_id"]."|卡号：".$citem["card_number"]."|";
            $card = $this->m_card->where(array("card_number" => $citem["card_number"]))->find();
            $mul_data = max($card["package_data_add"] - $citem["package_data"],0);
            $new_flow = $card["package_data_month"] + $mul_data;
            $telecom = new \Wulian\Lib\telecom();
            $telecom->poolNbr = $this->wl_config['flow_pool_id'];
            $package_data = round($new_flow / $this->wl_config["proportion"], 0);
            $log .= "流量值:".$package_data."|";
            $result = $telecom->modifyPoolMember($citem["card_number"], (int)$package_data);
            if ($result["Response"]["RspCode"] == '0000') {
                $log .= "成功";
                $res1 = $this->m_card->where(array("card_number" => $citem["card_number"]))->save(array("package_data_add" => $mul_data));
                if($res1)$this->m_cron->where(array("cron_id" => $citem["cron_id"]))->save(array("cron_status" => 1));
            }else{
                $log .= "失败|";
            }
        }
        $cost_time = time() - $start_time;
        addCronLog(7,$log,$cost_time);
    }
}